<template>
  <div class="chart">
    <div :id="data.id" height="100%" width="100%" />
  </div>
</template>

<script>
import echarts from 'echarts'

const colors = [
  [0.3, '#67e0e3'],
  [0.7, '#37a2da'],
  [1, '#fd666d']
]
export default {
  props: {
    chartData: {
      type: Object,
      default: () => {
        return {
          id: 'card' + Date.now(),
          value: 0
        }
      }
    }
  },
  data() {
    return {
      data: {
        id: 'card' + Date.now(),
        value: 0
      }
    }
  },
  watch: {
    // tips 是会变更的数据，所以进行监听
    chartData: {
      handler(newData) {
        this.data = newData
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    getData() {
      this.chart = echarts.init(document.getElementById(this.data.id))
      this.chart.setOption({
        series: [
          {
            type: 'gauge',
            center: ['50%', '55%'],
            radius: '80%',
            min: 0,
            max: 3,
            splitNumber: 10,
            axisLine: {
              lineStyle: {
                width: 10,
                color: colors
              }
            },
            pointer: {
              width: 3,
              length: '50%',
              itemStyle: {
                color: '#fff'
              }
            },
            axisTick: {
              distance: 10,
              length: 3,
              lineStyle: {
                color: '#fff',
                width: 1
              }
            },
            splitLine: {
              length: 10,
              lineStyle: {
                color: '#fff',
                width: 1
              }
            },
            axisLabel: {
              color: '#fff',
              distance: 5,
              fontSize: 8
            },
            detail: {
              valueAnimation: true,
              formatter: '{value} kw·h',
              fontSize: 10,
              fontWeight: 'bold',
              color: this.getColor(this.data.value)
            },
            data: [
              {
                value: this.data.value
              }
            ]
          }
        ]
      })
    },
    getColor(value) {
      for (const item of colors) {
        if (value / 100 <= item[0]) {
          return item[1]
        }
      }
      return colors[0][1]
    }
  }
}
</script>

<style lang="scss" scoped>
.chart {
  > div {
    height: 180px;
  }
}
</style>
